
import React, { forwardRef, ForwardRefRenderFunction, useImperativeHandle, useMemo } from 'react'
import { Form as AntdForm, Input, DatePicker } from 'antd'
import { CommonComponenetProps } from '../../interface'
import dayjs from 'dayjs'

export interface FormRef {
  submit: () => void
}

const Form: ForwardRefRenderFunction<FormRef, CommonComponenetProps> = ({ children, onFinish }, ref) => {

  // 返回一个 form 实例对象
  const [ form ]  = AntdForm.useForm()

  // 暴露给父组件的方法
  useImperativeHandle(ref, () => {
    return {
      submit: () => {
        form.submit()
      }
    }
  }, [form])

  const formItems = useMemo(() => {
    return React.Children.map(children, (item: any) => {
      return {
        label: item.props?.label,
        name: item.props?.name,
        type: item.props?.type,
        id: item.props?.id,
        rules: item.props?.rules,
      }
    })
  }, [children])

  function save(values: any){
    // 需要对 DatePicker 的 value 做下处理，因为值是 dayjs 对象，需要 format 一下拿到字符串值
    Object.keys(values).forEach((key: string) => {
      if (dayjs.isDayjs(values[key])){
        values[key] = values[key].format('YYYY-MM-DD')
      }
    })
    onFinish(values)
  }

  return (
    <AntdForm
      name="form"
      labelCol={{ span: 5 }}
      wrapperCol={{ span: 18 }}
      form={form}
      onFinish={save} // 提交表单且数据验证成功后回调事件: submit -> onFinish(save) => onFinish(传过来的 onFinish)
    >
      {formItems.map((item: any) => {
        return (
          <AntdForm.Item
            key={item.name}
            name={item.name}
            label={item.label}
            rules={
              item.rules === 'required' ? [{ required: true, message: '不能为空' }] : []
            }
          >
            {item.type === 'input' && <Input />}
            {item.type === 'date' && <DatePicker />}
          </AntdForm.Item>
        ) 
      })}
    </AntdForm>
  )
}

export default forwardRef(Form)